<template>
  <view>
    <!-- 头像昵称区域 -->
    <view class="top-top">
      <view class="top-box" @click="enterUserHome">
        <image :src="theUserAvatar" class="avatar"></image>
        <view class="top-a">
          <view class="nickname">{{ theUserName }}</view>
          <view class="send_time">{{ sendTime }}</view>
        </view>
      </view>
      <!-- 关注按钮 -->
      <button
        v-if="showFollowButton"
        class="follow-btn"
        :class="{ followed: isFollowed }"
        @click="followUser"
      >
        {{ isFollowed ? "已关注" : "关注" }}
      </button>
      <view class="requireNum">
        需人数&nbsp;{{ requiredPeople }}&nbsp;
        <br />
        已加入&nbsp;{{ joinPeople }}&nbsp;
      </view>
    </view>
    <!-- 标题与组团详情 -->
    <view class="tuan_info">
      <view class="tuan_title">
        {{ tuanTitle }}
      </view>
      <view class="tuan_detail">
        <text>{{ tuanDetail }}</text>
      </view>
      <view
        class="image-container"
        v-for="(image, index) in images"
        :key="index"
      >
        <image :src="image" class="tuan-image" mode="widthFix"></image>
      </view>
      <!-- 标签数组显示 -->
      <view class="tags-container" v-if="tagName && tagName.length > 0">
        <view class="tag" v-for="(tag, tagIndex) in tagName" :key="tagIndex">{{
          tag
        }}</view>
      </view>

      <view class="twoTime">
        开始时间：{{ groupDetailVo.tuan.beginTime }}
        <br>
        结束时间：{{ groupDetailVo.tuan.endTime }}
        <br>
        距离：{{ distance }}km
      </view>

      <view class="view-upvote">
        <view class="viewUpvoteBox">
          <image src="/static/my-icons/view.png" mode="aspectFill" />
          <view class="count">
            {{ groupDetailVo.tuan.viewCount }}
          </view>
        </view>
        <view class="viewUpvoteBox">
          <image
            v-if="isUpvote"
            @click="upvote"
            src="/static/my-icons/hasUpvote.png"
            mode="aspectFill"
          />
          <image
            v-else
            @click="upvote"
            src="/static/my-icons/upvote.png"
            mode="aspectFill"
          />
          <view class="count">
            {{ storageUpvoteCount }}
          </view>
        </view>
      </view>
    </view>
    <!-- 加入组团按钮 -->
    <view class="join-group-btn-container">
      <view class="collect-icon" @click="collectGroup">
        <image
          v-if="isCollected"
          src="../../static/tab_icons/collect-active.png"
          mode="'scaleToFill'"
        />
        <image
          v-else
          src="../../static/tab_icons/collect.png"
          mode="'scaleToFill'"
        />
      </view>
      <button v-if="groupDetailVo.tuan.tuanStatus===1" class="join-group-btn" @click="joinGroup">加入组团</button>
      <button v-else class="tuanEnd">组团已结束</button>
    </view>
    <!-- 弹出框 -->
    <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog
        type="info"
        title="验证问题"
        content="请回答验证问题"
        :before-close="true"
        @confirm="confirmJoin()"
        @close="cancelJoin"
      >
        <view>
          <text class="theQuestion">问题：{{ question }}</text>
          <input
            class="joinInput"
            v-model="joinReason"
            placeholder="请回答验证问题"
          />
        </view>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 评论组件 -->
    <group-comments :tuanId="tuanId"></group-comments>
  </view>
</template>

<script>
import { mapState } from "vuex";

export default {
  computed: {
    ...mapState("m_user", ["userinfo"]),
    showFollowButton() {
      return this.theUserId !== uni.getStorageSync("userId");
    },
  },
  data() {
    return {
      userId: uni.getStorageSync("userId"),
      theUserId: "", //组团发布者id
      theUserName: "", //组团发布者昵称
      theUserAvatar: "", //组团发布者头像
      tuanId: "",
      tuanTitle: "",
      tuanDetail: "",
      sendTime: "",
      images: [],
      tagName: [],
      requiredPeople: "",
      joinPeople: "",
      groupDetailVo: {},
      isFollowed: "", // 关注状态
      needAgree: "",
      joinReason: "",
      question: "",
      isCollected: false,
      isUpvote: false,
      storageUpvoteCount: "",
      distance: "",
      long2: "",
      lat2: "",
    };
  },
  onLoad(options) {
    // 获取组团详情
    this.getGroupById(options);
    // 判断是否已经收藏
    this.hasCollected(options.tuanId);
    //判断是否已经点赞
    this.hasUpvote(options.tuanId);
    const long = uni.getStorageSync("longitude");
    const lat = uni.getStorageSync("latitude");

  },

  methods: {
    //点赞
    upvote() {
      console.log("点赞按钮被点击");
      uni.$http
        .post(`/upvote/upvote?userId=${this.userId}&tuanId=${this.tuanId}`)
        .then((res) => {
          const responseData = res.data;
          if (responseData.code === 200) {
            if (!this.isUpvote) {
              this.storageUpvoteCount = this.storageUpvoteCount + 1;
            } else {
              this.storageUpvoteCount = this.storageUpvoteCount - 1;
            }
            this.isUpvote = !this.isUpvote;
            console.log(responseData);
            uni.showToast({
              title: responseData.data,
              icon: "none",
              duration: 2000,
            });
          } else {
            console.log("点赞失败", responseData);
            uni.showToast({
              title: responseData.message,
              icon: "none",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          console.error("点赞失败", err);
          uni.showToast({
            title: "点赞失败",
            icon: "none",
            duration: 2000,
          });
        });
    },
    //进入用户主页
    enterUserHome() {
      uni.navigateTo({
        url: `/subpkg/user_home/user_home?theUserId=${this.theUserId}`,
      });
    },
    collectGroup() {
      console.log("收藏按钮被点击");
      uni.$http
        .post(
          `/collect/collectGroup?tuanId=${this.tuanId}&userId=${this.userId}`
        )
        .then((res) => {
          const responseData = res.data;
          if (responseData.code === 200) {
            this.isCollected = !this.isCollected;
            console.log(responseData);
            uni.showToast({
              title: responseData.data,
              icon: "none",
              duration: 2000,
            });
          } else {
            console.log("收藏失败", responseData);
            uni.showToast({
              title: "收藏失败",
              icon: "none",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          console.error("收藏失败", err);
          uni.showToast({
            title: "收藏失败",
            icon: "none",
            duration: 2000,
          });
        });
    },
    hasCollected(tuanId) {
      // 判断是否已经收藏
      uni.$http
        .get(`/collect/hasCollected?tuanId=${tuanId}&userId=${this.userId}`)
        .then((res) => {
          const responseData = res.data;
          if (responseData.code === 200) {
            this.isCollected = responseData.data;
            console.log("判断收藏状态", responseData.data);
          } else {
            console.log("判断收藏状态失败", responseData);
          }
        })
        .catch((err) => {
          console.error("判断收藏状态失败", err);
        });
    },
    hasUpvote(tuanId) {
      // 判断是否已经点赞
      uni.$http
        .get(`/upvote/hasUpvote?tuanId=${tuanId}&userId=${this.userId}`)
        .then((res) => {
          const responseData = res.data;
          if (responseData.code === 200) {
            this.isUpvote = responseData.data;
            console.log("判断点赞状态", responseData.data);
          } else {
            console.log("判断点赞状态失败", responseData);
          }
        })
        .catch((err) => {
          console.error("判断点赞状态失败", err);
        });
    },

    getGroupById(options) {
      if (options && options.tuanId) {
        const tuanId = options.tuanId;
        if (!isNaN(tuanId)) {
          uni.$http
            .get(`/tuan/getGroupById/?tuanId=${tuanId}&userId=${this.userId}`)
            .then((res) => {
              const responseData = res.data;
              if (responseData.code === 200) {
                this.groupDetailVo = responseData.data;
                this.theUserId = this.groupDetailVo.theUserId;
                this.theUserName = this.groupDetailVo.theUserName;
                this.theUserAvatar = this.groupDetailVo.theUserAvatar;
                this.tuanId = this.groupDetailVo.tuan.tuanId;
                this.tuanTitle = this.groupDetailVo.tuan.tuanTitle;
                this.tuanDetail = this.groupDetailVo.tuan.tuanDetail;
                this.sendTime = this.groupDetailVo.tuan.sendTime;
                this.images = this.groupDetailVo.images || [];
                this.tagName = this.groupDetailVo.tagName;
                this.requiredPeople = this.groupDetailVo.tuan.requiredPeople;
                this.joinPeople = this.groupDetailVo.tuan.joinPeople;
                this.isFollowed = this.groupDetailVo.isFollowed;
                this.needAgree = this.groupDetailVo.tuan.needAgree;
                this.question = this.groupDetailVo.tuan.question;
                this.storageUpvoteCount = this.groupDetailVo.tuan.upvoteCount;
                this.long2 = this.groupDetailVo.tuan.longitude;
                this.lat2 = this.groupDetailVo.tuan.latitude;

                // 计算 distance
                const long = uni.getStorageSync("longitude");
                const lat = uni.getStorageSync("latitude");
                this.distance = this.calculateDistance(lat, long, this.lat2, this.long2).toFixed(2);

                console.log("获取组团信息成功", responseData.data);
              } else {
                console.error("获取组团信息失败", responseData);
              }
            })
            .catch((err) => {
              console.error("获取组团信息失败", err);
            });
        } else {
          console.warn("无效的组团id:", options.tuanId);
        }
      } else {
        console.warn("缺少组团id");
      }
    },

    joinGroup() {
      // 添加加入组团的逻辑
      console.log("加入组团按钮被点击");
      if (this.userId === this.theUserId) {
        uni.showToast({
          title: "无需再加入自己的组团",
          icon: "none",
          duration: 2000,
        });
      } else {
        if (this.needAgree === true) {
          this.$refs.popup.open();
        } else {
          this.joinGroupRequest();
        }
      }
    },

    joinGroupRequest() {
      uni.$http
        .post("/tuan/joinGroup", {
          tuanId: this.tuanId,
          userId: this.userId,
          joinReason: this.joinReason,
        })
        .then((res) => {
          const responseData = res.data;
          if (responseData.code === 200) {
            console.log("加入组团成功", responseData.data);
            uni.showToast({
              title: responseData.data,
              icon: "none",
              duration: 2000,
            });
          } else {
            console.log("加入组团失败", responseData);
            uni.showToast({
              title: responseData.message,
              icon: "none",
              duration: 2000,
            });
          }
        })
        .catch((err) => {
          console.error("加入组团失败:", err);
          uni.showToast({
            title: "加入组团失败",
            icon: "none",
            duration: 2000,
          });
        });
    },

    confirmJoin() {
      if (this.joinReason.trim() === "") {
        uni.showToast({
          title: "请回答验证问题",
          icon: "none",
          duration: 2000,
        });
      } else {
        this.joinGroupRequest();
        this.$refs.popup.close();
      }
    },

    cancelJoin() {
      this.$refs.popup.close();
    },

    followUser() {
      this.isFollowed = !this.isFollowed; // 切换关注状态
      const followDto = {
        userId: this.userId,
        followedUserId: this.theUserId,
        isFollowed: this.isFollowed,
      };
      console.log("发送关注请求:", {
        userId: this.userId,
        followedUserId: this.theUserId,
        isFollowed: this.isFollowed,
      });
      uni.$http
        .post("/follow/followUser", followDto)
        .then((res) => {
          const responseData = res.data;
          if (responseData.code === 200) {
            if (this.isFollowed) {
              console.log("已关注");
              // 这里可以添加关注用户的逻辑
              uni.showToast({
                title: "关注成功~",
                icon: "none",
                duration: 2000,
              });
            } else {
              console.log("取消关注");
              // 这里可以添加取消关注的逻辑
              uni.showToast({
                title: "已取消关注",
                icon: "none",
                duration: 2000,
              });
            }
          }
        })
        .catch((err) => {
          console.error("关注/取消关注失败", err);
        });
    },
    calculateDistance(lat1, lon1, lat2, lon2) {
    const R = 6371; // 地球半径，单位为公里
    const dLat = this.deg2rad(lat2 - lat1);
    const dLon = this.deg2rad(lon2 - lon1);
    const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    const distance = R * c; // 距离，单位为公里

    // 格式化距离到小数点后一位
    return parseFloat(distance.toFixed(2));
},
deg2rad(deg) {
    return deg * (Math.PI / 180);
},
  },
};
</script>

<style lang="scss">
page {
  background-color: white;
  padding-bottom: 60px;
}

.top-top {
  display: flex;
  margin-top: 10px;
  margin-left: 5px;
  margin-right: 5px;
  justify-content: space-between;

  .requireNum {
    margin-top: 11px;
    color: #938e8e;
    font-size: 11px;
    text-align: right;
    margin-left: auto;
    margin-right: 15px;
    line-height: 18px;
  }

  .follow-btn {
    margin-top: 11px;
    height: 30px;
    font-size: 12px;
    background-color: #fbd269;
    color: white;
    border: none;
    border-radius: 20px;
    text-align: center;

    &.followed {
      background-color: #ccc;
      color: #666;
    }
  }
}

.tuan_info {
  padding: 15px;

  .tuan_title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
  }

  .tuan_detail {
    margin-bottom: 20px;
  }

  .image-container {
    margin-bottom: 8px;

    .tuan-image {
      width: 100%;
      display: block;
      border-radius: 7px;
    }
  }
}

.top-box {
  height: 95rpx;
  width: 205px;
  display: flex;
  margin-top: 8px;
  padding-left: 8px;
  position: relative;

  .avatar {
    display: block;
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }

  .top-a {
    display: flex;
    flex-direction: column;
    padding-left: 30rpx;

    .nickname {
      color: #1d1c1c;
      font-size: 14px;
      max-width: 139px;
      white-space: nowrap; /* 防止换行 */
      overflow: hidden; /* 隐藏溢出内容 */
      text-overflow: ellipsis; /* 省略号显示 */
    }

    .send_time {
      color: #6a6666;
      font-size: 12px;
      margin-top: 5px;
    }
  }
}
.twoTime {
  color: #6a6666;
      font-size: 12px;
      margin-top: 5px;
}
.tags-container {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;

  .tag {
    background-color: #f0f0f0;
    color: #333;
    padding: 5px 10px;
    border-radius: 15px;
    margin-right: 5px;
    margin-bottom: 5px;
    font-size: 14px;
  }
}

// 添加加入组团按钮样式
.join-group-btn-container {
  padding-top: 5px;
  display: flex;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 50px;
  z-index: 1000; // 确保按钮在最上层
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.171);
}
.collect-icon {
  width: 35px;
  height: 35px;
  margin-left: 12px;
  margin-top: 4px;
  image {
    width: 100%;
    height: 100%;
  }
}
.join-group-btn {
  width: 80%;
  height: 90%;
  font-size: 17px;
  color: rgb(96, 96, 96);
  background-color: #fbd269;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.171);
  border: none;
  text-align: center;
  border-radius: 40px;
  margin-right: 18px;
}

.joinInput {
  margin-top: 8px;
  width: auto;
  border-radius: 5px;
  padding: 5px 5px;
  background-color: rgb(255, 255, 255);
  border: 1px solid rgb(179, 175, 175);
}

.theQuestion {
  line-height: 22px;
  flex-wrap: wrap; /* 允许换行 */
}

.view-upvote {
  padding-top: 10px;
  display: flex;
  height: 40px;
  .viewUpvoteBox {
    width: 50vw;
    justify-content: center;
    align-items: center;
    text-align: center;
    image {
      width: 25px;
      height: 25px;
    }
    .count {
      color: #707070;
      font-size: 12px;
    }
  }
}
.tuanEnd {
  width: 80%;
  height: 90%;
  font-size: 17px;
  color: rgb(96, 96, 96);
  background-color: #d7d7d7;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.171);
  border: none;
  text-align: center;
  border-radius: 40px;
  margin-right: 18px;
}
</style>